package com.rain.cy.framework.utils;


import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SendMsgUtils {


    @Data
    @Accessors(chain = true)
    static class DingTalkVo {
        private String msgtype;
        private Map<String, String> text = new HashMap<>();
    }

    private static WebClient webClient;

    @Autowired
    public void setWebClient(WebClient webClient) {
        SendMsgUtils.webClient = webClient;
    }

    /**
     * 发送钉钉消息
     *
     * @param msg
     */
    public static void sendDingtalkMsg(String msg) {
        DingTalkVo dingTalkVo = new DingTalkVo();
        dingTalkVo.setMsgtype("text").getText().put("content", "[异常通知]"+msg);
        String s = JSON.toJSONString(dingTalkVo);
        webClient.post().uri("https://oapi.dingtalk.com/robot/send?access_token=8dd0775da92baf8ea2d47249f3cdf786a3df8166121aa9ec7ff3e196b4b317fb")
                .header("Content-Type", "application/json; charset=utf-8")
                .body(Mono.just(s), String.class)
                .retrieve()
                .bodyToMono(String.class)
                .doOnError(WebClientResponseException.class, err -> {
                    log.error("send dingtalk msg error ,  status:{},msg:{}", err.getRawStatusCode(), err.getResponseBodyAsString());
                }).subscribe(e -> log.info("result = {}", e));
    }


}
